//
//  LVPhotoBrowserAnimator.swift
//  PhotoBrowser
//
//  Created by 刘伟 on 16/4/28.
//  Copyright © 2016年 刘伟. All rights reserved.
//

import UIKit

class LVPhotoBrowserAnimator: NSObject {
    var isPresented : Bool = false
}

extension LVPhotoBrowserAnimator : UIViewControllerTransitioningDelegate{

//    1.弹出动画交给谁去管理
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    
    //    2.结束动画交给谁去管理
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }

}

extension LVPhotoBrowserAnimator : UIViewControllerAnimatedTransitioning {

//    1.返回动画的执行时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 1.0
    }
    
//    2.可以获取转场的上下文:通过上下文获取到执行动画的view
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        isPresented ? animateForPresentView(transitionContext) : animateForDissmissView(transitionContext)

    }
    
    
//    3.设计弹出动画
    func animateForPresentView(transitionContext: UIViewControllerContextTransitioning){
    
//        1.取出弹出的view(控制器的view)
        /*UITransitionContextFromViewKey, and UITransitionContextToViewKey*/
        let presentView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        
//        2.将弹出的view自己加到containerVie中
        transitionContext.containerView()?.addSubview(presentView)
        
//        3.执行动画
        presentView.alpha = 0.0
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            presentView.alpha = 1.0
            }) { (_ ) -> Void in
                transitionContext.completeTransition(true)
        }
    }
    
//    4.设置消失动画
    func animateForDissmissView(transitionContext: UIViewControllerContextTransitioning){
    
//        1.取出消失的View
        let dissmissView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        
//        2.执行动画
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            dissmissView.alpha = 0.0
            }) { (_ ) -> Void in
                dissmissView.removeFromSuperview()
                transitionContext.completeTransition(true)
        }
    
    
    
    }
    
}


























